package red.yancloud.www.ui.activity

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.appcompat.widget.AppCompatEditText
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.Gson
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_my_bookshelf.*
import kotlinx.android.synthetic.main.activity_my_bookshelf.errorView
import kotlinx.android.synthetic.main.activity_my_bookshelf.smartRefreshLayout
import red.yancloud.www.R
import red.yancloud.www.base.BaseRefreshActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.BookRecord
import red.yancloud.www.internet.bean.MyBookShelf
import red.yancloud.www.internet.bean.ReadBookType
import red.yancloud.www.manager.DatabaseManager
import red.yancloud.www.ui.adapter.MyBookshelfRecyclerAdapter
import red.yancloud.www.ui.adapter.RecycleViewDivider
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.TimeFormatUtil
import red.yancloud.www.util.ToastUtils
import java.text.SimpleDateFormat
import java.util.*


/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/11 17:45
 * E_Mail：yh131412hys@163.com
 * Describe：我的书架
 * Change：
 * @Version：V1.0
 */
class MyBookshelfActivity : BaseRefreshActivity(), View.OnClickListener {

    private val TAG = "MyBookshelfActivity"

    private lateinit var mAdapter:MyBookshelfRecyclerAdapter
    private lateinit var myBookshelfActivitySearchEt: AppCompatEditText

    override val layoutId: Int
        get() = R.layout.activity_my_bookshelf

    override fun initData() {
        super.initData()

        RedCloudApis.getInstance()
            .bookRecord(UserInfoShardPreference.instance.uid,page.toString(), limit,object : Observer<BookRecord> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: BookRecord) {

                }

                override fun onError(e: Throwable) {
                }
            })
    }

    override fun getRefreshDataList() {
        getBookcaseList()
    }

    override fun configViews() {
        super.configViews()

        myBookshelfActivity_back_iv.setOnClickListener(this)
        myBookshelfActivity_share_iv.setOnClickListener(this)

        myBookshelfActivitySearchEt = findViewById(R.id.myBookshelfActivity_search_et)
    }

    override fun initRecyclerView() {
        myBookshelfActivity_rV.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        myBookshelfActivity_rV.addItemDecoration(
            RecycleViewDivider(
                this,
                DividerItemDecoration.VERTICAL,
                ScreenUtils.dpToPx(10f).toInt(),
                R.color.color_f5
            )
        )
        mAdapter= MyBookshelfRecyclerAdapter(R.layout.item_bookshelf_list)
        mAdapter.onItemClickListener = object :BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                startActivity(
                    Intent(this@MyBookshelfActivity, BookInfoActivity::class.java)
                        .putExtra("bookId",(adapter!!.data[position] as MyBookShelf.DataBean.RecordsBean).bookid)
                        .putExtra(
                            "url",
                            "${Constants.API_BASE_RED_CLOUD_URL}article/?bid=${(adapter.data[position] as MyBookShelf.DataBean.RecordsBean).bookid}"
                        )
                )
            }
        }
        mAdapter.onItemChildClickListener=object :BaseQuickAdapter.OnItemChildClickListener{
            override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                RedCloudApis.getInstance().myBookDelte(UserInfoShardPreference.instance.uid,(mAdapter.data[position] as MyBookShelf.DataBean.RecordsBean).bookid,object : Observer<ReadBookType> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: ReadBookType) {

                        if (t.code == Constants.SYSTEM_OK) {

                            DatabaseManager.instance.deleteBook((mAdapter.data[position] as MyBookShelf.DataBean.RecordsBean).bookid)
                            mAdapter.remove(position)
                            ToastUtils.showToast("删除成功")
                        }
                    }

                    override fun onError(e: Throwable) {
                    }
                })
            }
        }
        myBookshelfActivity_rV.adapter = mAdapter
    }

    private fun getBookcaseList() {

        RedCloudApis.getInstance().bookcase(UserInfoShardPreference.instance.uid, page.toString(), limit, object : Observer<MyBookShelf> {

                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: MyBookShelf) {

                    val toJson = Gson().toJson("\u96be\u5fd8\u5ce5\u5d58\u5c81\u6708")
                    Log.d(TAG, toJson.toString())

                    if (t.code == Constants.SYSTEM_OK) {

                        if (t.data != null&&t.data.page!=null) {

                            totalPage = t.data.page.totalPage

                            if (t.data.page.count.toInt()==0) {

                                errorView.visibility=View.VISIBLE
                                smartRefreshLayout.visibility=View.GONE
                                loadingDialog.dismiss()
                                return
                            }
                        }

                        if(t.data.records != null && t.data.records.size > 0){

                            if (page==1) {

                                mAdapter.data.clear()
                                mAdapter.addData(t.data.records)
                                smartRefreshLayout.resetNoMoreData()
                                smartRefreshLayout.finishRefresh()
                            }else {

                                mAdapter.addData(t.data.records)
                                smartRefreshLayout.finishLoadMore()
                            }
                        }else{

                            if (page==1){

                                smartRefreshLayout.finishRefresh()

                                errorView.visibility=View.VISIBLE
                                smartRefreshLayout.visibility=View.GONE
                            }else{

                                ToastUtils.showToast(getString(R.string.data_all_load))
                                smartRefreshLayout.finishLoadMore()
                            }
                        }
                    }else{

                        errorView.visibility=View.VISIBLE
                        smartRefreshLayout.visibility=View.GONE
                    }
                }

                override fun onError(e: Throwable) {

                    errorView.visibility=View.VISIBLE
                    smartRefreshLayout.visibility=View.GONE
                }
            })
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.myBookshelfActivity_back_iv -> finish()
            R.id.myBookshelfActivity_share_iv -> {
            }
        }
    }

    private fun initSmartRefreshLayout() {

        val mClassicsHeader = smartRefreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis()))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))

//        smartRefreshLayout.setEnableAutoLoadMore(true)//开启自动加载功能（非必须）
        smartRefreshLayout.setOnRefreshListener(OnRefreshListener {

            if (!NetworkUtils.isConnected(this)) {
                errorView.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishRefresh()
                return@OnRefreshListener
            }
            page=1
            getBookcaseList()
//            refreshLayout.layout.postDelayed({
//                mAdapter.refresh(initData())
//                refreshLayout.finishRefresh()
//                refreshLayout.resetNoMoreData()//setNoMoreData(false);
//            }, 2000)
        })
        smartRefreshLayout.setOnLoadMoreListener(OnLoadMoreListener { refreshLayout ->

            if (page>=totalPage){

                ToastUtils.showToast(getString(R.string.data_all_load))
                smartRefreshLayout.finishLoadMoreWithNoMoreData()//将不会再次触发加载更多事件
                return@OnLoadMoreListener
            }
            if (!NetworkUtils.isConnected(this)) {
                errorView.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishLoadMore()
                return@OnLoadMoreListener
            }
            page++
            getBookcaseList()
//            refreshLayout.layout.postDelayed({
//                if (mAdapter.itemCount > 30) {
//                    Toast.makeText(application, "数据全部加载完毕", Toast.LENGTH_SHORT).show()
//                    refreshLayout.finishLoadMoreWithNoMoreData()//将不会再次触发加载更多事件
//                } else {
//                    mAdapter.loadMore(initData())
//                    refreshLayout.finishLoadMore()
//                }
//            }, 2000)
        })
    }
}
